<?php
namespace app\system\controller;

use app\common\model\ConfigGroupModel;
use think\Request;

class ConfigGroupController extends BaseController
{

    private $configGroupModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->configGroupModel = new ConfigGroupModel();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $list = $this->configGroupModel->order('group_sort asc')->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 添加用户
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try{
                $data   = $this->request->param();
                $result = $this->validate($data, [
                    'group_name|配置组'    => 'require',
                    'group_title|配置组名称' => 'require',
                    'group_sort|排序'     => 'number',
                ]);
                if (true !== $result) {
                    exception($result,40001);
                }
                $this->configGroupModel->addData($data);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('添加成功！', url('index'));
        }
        return $this->fetch();
    }

    /**
     * 修改数据
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            try{
                $data   = $this->request->param();
                $result = $this->validate($data, [
                    'group_name|配置组'    => 'require',
                    'group_title|配置组名称' => 'require',
                    'group_sort|排序'     => 'number',
                ]);
                if (true !== $result) {
                    exception($result,40001);
                }
                $this->configGroupModel->editData($data);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('修改成功！', url('index'));
        }
        $id   = $this->request->param('id');
        $info = $this->configGroupModel->get($id);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除数据
     */
    public function del()
    {
        try{
            $id = $this->request->param('id', 0);
            $this->configGroupModel->delData($id);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功！');
    }

}
